#include <condition_variable>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include "../../log/log.h"
 
std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;
 
void worker_thread()
{
    // wait until main() sends data
    LOG("unique_lock");
    std::unique_lock<std::mutex> lk(m);
    cv.wait(lk, []{ LOG("wiat, ready=%d", ready); return ready; });
 
    // after the wait, we own the lock
    LOG("Worker thread is processing data");
    data += " after processing";
 
    // send data back to main()
    processed = true;
    LOG("Worker thread signals data processing completed");
 
    // manual unlocking is done before notifying, to avoid waking up
    // the waiting thread only to block again (see notify_one for details)
    lk.unlock();
    cv.notify_one();
}
 
int main()
{
    LOG("in.");
    std::thread worker(worker_thread);
 
    data = "Example data";
    // send data to the worker thread
    {
        LOG("unique_lock");
        std::unique_lock<std::mutex> lk(m);
        LOG("ready = true");
        ready = true;
        LOG("main() signals data ready for processing");
    }
    cv.notify_one();
 
    // wait for the worker
    {
        LOG("unique_lock");
        std::unique_lock lk(m);
        cv.wait(lk, []{ LOG("wiat, ready=%d", ready); return processed; });
    }
    LOG("Back in main(), data = %s", data.c_str());
 
    worker.join();
}